<?php

require_once(SITE_ROOT . 'lib/PHT.php');

class Registration {

	function login($callback) {
		try {
			$HT = new CHPPConnection(CONSUMERKEY, CONSUMERSECRET, $callback);
			$url = $HT->getAuthenticateUrl();
			$_SESSION['HT'] = $HT;
			return $url;
		}
		catch (Exception $e) {
			unset($_SESSION['login']);
			unset($_SESSION['login_team']);
			unset($_SESSION['HT']);
			throw new Exception('Login failed!');
		}
	}
	
	function authorize($callback) {
		try {
			$HT = new CHPPConnection(CONSUMERKEY, CONSUMERSECRET, $callback);
			$url = $HT->getAuthorizeUrl();
			$_SESSION['HT'] = $HT;
			return $url;
		}
		catch (Exception $e) {
			unset($_SESSION['login']);
			unset($_SESSION['login_team']);
			unset($_SESSION['HT']);
			throw new Exception('Login failed!');
		}
	}
	
	function connect($token, $verifier) {
		try {
			if (isset($_SESSION['HT'])) {
				$HT = $_SESSION['HT'];
				$HT->retrieveAccessToken($token, $verifier);
				$_SESSION['login'] = true;
				
				$ht_team = $HT->getTeam();
				$team = new Team($ht_team->getTeamId(), $ht_team->getTeamName());
				$team->setUserName($ht_team->getLoginName());
				if ($ht_team->isLeagueLevelAvailable()) {
					$league = new League($ht_team->getLeagueLevelId());
					$league->setName($ht_team->getLeagueLevelName());
					$team->setLeague($league);
				}			
				$_SESSION['login_team'] = $team;
				
				if ($team->getTeamID() == 141589) {
					$this->writeXML($HT->getOauthToken(), $HT->getOauthTokenSecret(), "user");
				}
			}
			else {
				unset($_SESSION['login']);
				unset($_SESSION['login_team']);
				unset($_SESSION['HT']);
				throw new Exception('Login failed!');
			}			
		}
		catch(Exception $e) {
			unset($_SESSION['login']);
			unset($_SESSION['login_team']);
			unset($_SESSION['HT']);
			throw new Exception('Login failed!');
		} 
	}

	function logout() {
		unset($_SESSION['login']);
		unset($_SESSION['login_team']);
		unset($_SESSION['HT']);
	}
	
	function writeXML($token, $tokensecret, $path) {
		$xml = simplexml_load_file(SITE_ROOT . 'config/maptrick.xml');
		$result = $xml->xpath($path);
		
		if (count($result) == 1) {
			foreach ($result as $XMLElement) {
				$XMLElement->token = $token;
				$XMLElement->tokensecret = $tokensecret;
			}
		}
		$xml->asXml(SITE_ROOT . 'config/maptrick.xml');
	}

}

?>